package org.nobody.mallb2c.mallproduct.exception;

import lombok.extern.slf4j.Slf4j;
import org.nobody.common.exception.ResultCodeEnum;
import org.nobody.common.utils.R;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * @author 3489309323@qq.com
 * @create 2020-07-31-21:29
 * <p>
 * 集中处理所有异常
 */
@Slf4j
//@ResponseBody
//@ControllerAdvice(basePackages = "org.nobody.mallb2c.mallproduct.controller")
@RestControllerAdvice(basePackages = "org.nobody.mallb2c.mallproduct.controller")
public class MallExceptionControllerAdvice {
  @ExceptionHandler(value = MethodArgumentNotValidException.class)/*←所有异常都能处理*/
  public R handleValidException(MethodArgumentNotValidException e) {
    log.error("数据校验出现问题: {}, 异常类型: {}", e.getMessage(), e.getClass());

    BindingResult bindingResult = e.getBindingResult();
    HashMap<String, String> errorMap = new HashMap<>();
    bindingResult.getFieldErrors().forEach(fieldError -> {
      errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
    });
    return R.error(ResultCodeEnum.VAILD_EXCEPTION.getCode(), ResultCodeEnum.VAILD_EXCEPTION.getMsg()).put("data", errorMap);
  }

  @ExceptionHandler(value = Throwable.class)
  public R handleException(Throwable throwable){
    log.error("未知错误:",throwable);
    return R.error(ResultCodeEnum.UNKNOW_EXCEPTION.getCode(),ResultCodeEnum.UNKNOW_EXCEPTION.getMsg());
  }
}
